import {findFatherTree} from '@u/utils-cjy'
import {authRoutes} from '../../config/routers'

export default {
  namespace: 'menuList',
  state: {
    openKeys: [],
    selectedKeys: [],
    collapsed: false,
    firstHide: false,
    breadcrumb: [],
    menuList: []
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload }
    },
  },
  effects: {
    * menuChange({history}, {put, select}) {
      const {collapsed, selectedKeys} = yield select(s => s.menuList)
      const {pathname} = history
      let breadcrumb = findFatherTree(authRoutes, pathname)
      let openKeys = []
      let newArr = [].concat(breadcrumb)
      let newSelectedKeys = newArr.pop()
      if (newSelectedKeys) {
        let link = newSelectedKeys.path
        if (newSelectedKeys.hidden) {
          newSelectedKeys = [link.substring(0, link.lastIndexOf('/'))]
        } else {
          newSelectedKeys = [link]
        }
      } else {
        newSelectedKeys = []
      }
      newArr.forEach(v => {
        openKeys.push(v.path)
      })
      if (newSelectedKeys[0] !== selectedKeys[0]) {
        yield put({
          type: 'commonTable/init'
        })
      }
      yield put({
        type: 'save',
        payload: {
          breadcrumb,
          selectedKeys: newSelectedKeys,
          openKeys: collapsed? []:openKeys
        }
      })
      // console.log(breadcrumb)
      // console.log(newSelectedKeys[0], selectedKeys[0])
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(e => {
        dispatch({
          type: 'menuChange',
          history: e
        })
      })
    },
  },
}
